package edu.npu.cv.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.npu.cv.constant.ResultCode;
import edu.npu.cv.dao.PublicationDAO;
import edu.npu.cv.entity.PageDO;
import edu.npu.cv.entity.PublicationDO;
import edu.npu.cv.entity.ResultDO;
import edu.npu.cv.service.PublicationService;
import edu.npu.cv.utils.PageQueryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author lelechang
 * @description: 服务层
 * @version: V1.0
 */
@Service
public class PublicationServiceImpl implements PublicationService {

    @Resource
    private PublicationDAO publicationDao;

    /**
     * 从数据库中获取论文列表
     *
     * @return
     */
    public List<PublicationDO> findAll() {
        return publicationDao.selectList(new QueryWrapper<PublicationDO>());
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public PublicationDO findById(String id) {
        return publicationDao.selectById(id);
    }

    /**
     * 分页查询论文
     * 返回论文
     */
    @Override
    public ResultDO<PageDO> findAll(PageQueryUtil pageQueryUtil){
        List<PublicationDO> publicationDOS = publicationDao.getPublications(pageQueryUtil);
        int total = getPublicationCount();
        return new ResultDO<PageDO>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS,
                new PageDO(total, pageQueryUtil.getLimit(), pageQueryUtil.getPage(),
                        publicationDOS));
    }

    @Override
    public int getPublicationCount() {
        return publicationDao.selectCount(null).intValue();
    }

    @Override public ResultDO<Void> deleteByIds(Long[] ids) {
        int result = publicationDao.deleteBatchIds(Arrays.asList(ids));
        if (result > 0) {
            return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
        } else {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
        }
    }

    @Override
    public PublicationDO getPublicationDOById(long id) {
        return publicationDao.selectById(id);
    }

    @Override public ResultDO<Void> save(PublicationDO publicationDO) {
        int result = publicationDao.insert(publicationDO);
        if (result > 0) {
            return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
        } else {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
        }
    }

    @Override public ResultDO<Void> update(PublicationDO publicationDO) {
        int result = publicationDao.updateById(publicationDO);
        if (result > 0) {
            return new ResultDO<>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
        } else {
            return new ResultDO<>(false, ResultCode.DB_ERROR, ResultCode.MSG_DB_ERROR);
        }
    }
}
